<template>
  <div class="bg-white rounded pt-4 pb-4 pl-6 pr-6 h-full">
    <px-radio-group v-model="queryParams.machineTask" @change="radioChange">
      <px-radio-button v-for="item in areas" :key="item.value" :label="item.label" :value="item.value" />
    </px-radio-group>
    <px-form
      ref="formRef"
      class="custom-form-ui equip-form"
      :model="queryParams"
      label-position="right"
      label-width="120px"
      style="padding-top: 14px"
    >
      <px-form-item label="维度" class="w-32">
        <px-select v-model="queryParams.timePeriod" placeholder="请选择" style="width: 210px" filterable @change="timechange">
          <px-option v-for="dict in dimensionList" :key="dict.itemValue" :label="dict.itemName" :value="dict.itemValue" />
        </px-select>
      </px-form-item>
      <px-form-item v-if="queryParams.timePeriod == 'year'" label="年份" style="width: 390px">
        <yearPicker :labelWidth="0" labelText="" :initYear="dateValue" @updateTimeRange="updateStatisticYear" />
      </px-form-item>
      <px-form-item v-if="queryParams.timePeriod == 'months'" label="时间" style="width: 390px">
        <px-date-picker
          v-model="dateRangeMonth"
          type="monthrange"
          range-separator="-"
          start-placeholder="开始月份"
          end-placeholder="结束月份"
          placeholder="请选择"
          format="YYYY-MM"
          value-format="YYYY-MM"
          @change="changeTimeMonth"
        />
      </px-form-item>
      <px-form-item v-if="queryParams.timePeriod == 'day'" label="时间" style="width: 430px">
        <px-date-picker
          v-model="dateRangeDay"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          placeholder="请选择"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          :default-time="defaultTime"
          @change="changeTimeDay"
        />
      </px-form-item>
      <px-form-item v-if="queryParams.timePeriod == 'minutes'" label="时间" style="width: 430px">
        <px-date-picker
          v-model="dateRangeMin"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始日期时间"
          end-placeholder="结束日期时间"
          format="YYYY-MM-DD HH:mm"
          value-format="YYYY-MM-DD HH:mm"
          @change="changeTimeMinutes"
        />
      </px-form-item>
      <px-button type="primary" @click="queryData">查询</px-button>
      <px-button @click="resetTable">重置</px-button>
    </px-form>
    <div class="h-auto w-full">
      <div ref="chartContainer" :style="{ width: '100%', height: _height }" />
    </div>
  </div>
</template>
<script setup lang="ts">
defineOptions({
  name: "CLASS_MACHINE_FREEZE_BUILD_STATISTICS_DCC"
});
import { ref, onMounted, nextTick, reactive, onBeforeUnmount, computed } from "vue";
import dayjs from "dayjs";
import * as echarts from "echarts";
import { queryDCCFutureAPI } from "@/api/machineFreezeHouseAPI";
import { queryChildByTypeCodeAndItemValue } from "@/api/machineClass";
import yearPicker from "@/views/common/energy/components/yearPicker.vue";
import { DomType } from "@/hooks/types";
import { PxMessage } from "px-ui";
interface Props {
  height?: number;
}
const props = withDefaults(defineProps<Props>(), {
  height: 350
});
const _height = computed(() => `${props.height}px`);

const defaultTime: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)]; // 时间选择器默认 xxxx-xx-xx 00:00:00-xxxx-xx-xx 23:59:59
enum TimePeriodEnum {
  MINUTES = "minutes",
  DAY = "day",
  MONTHS = "months",
  YEAR = "year"
}
// area tab
const areas = ref([]);
const getArea = async () => {
  // 数据字典
  const res: any = await queryChildByTypeCodeAndItemValue({
    value: `ALGORITHM_LIST_PARAM`,
    typeCode: "ALGORITHM"
  });
  if (!res || !Array.isArray(res)) {
    return;
  }
  let a = res.find(e => e.itemValue === "DCC_SAMPLE")?.itemDesc;
  areas.value = JSON.parse(a).map(e => {
    return { label: e, value: e };
  });
  queryParams.value.machineTask = areas.value[0].value;
};
const queryParams = ref<any>({
  startTime: dayjs().subtract(1, "hour").format("YYYY-MM-DD HH:mm"),
  endTime: dayjs().format("YYYY-MM-DD HH:mm"),
  timePeriod: TimePeriodEnum.MINUTES,
  machineTask: ""
}); // 查询条件
const dateRangeMonth = ref([]);
const dateRangeDay = ref([]); //以Day为基础的时间范围
const dimensionList = [
  {
    itemName: "分钟",
    itemValue: TimePeriodEnum.MINUTES
  }
  // {
  //   itemName: "日",
  //   itemValue: TimePeriodEnum.DAY
  // },
  // {
  //   itemName: "月",
  //   itemValue: TimePeriodEnum.MONTHS
  // },
  // {
  //   itemName: "年",
  //   itemValue: TimePeriodEnum.YEAR
  // }
];
const dateValue = ref<any>({ startYear: new Date().getFullYear() - 6, endYear: new Date().getFullYear() }); //时间数据

function formatDate(date, type?, monthStart?, monthEnd?) {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");

  const h = date.getHours().toString().padStart(2, "0");
  const m = date.getMinutes().toString().padStart(2, "0");
  const s = date.getSeconds().toString().padStart(2, "0");
  if (type) {
    if (monthStart == "Start") {
      return `${year}-${month}-01 00:00:00`;
    } else {
      return `${year}-${month}-31 23:59:59`;
    }
  } else {
    return `${year}-${month}-${day} ${h}:${m}:${s}`;
  }
}
//初始化月时间
function initDateOfMonth() {
  const end = new Date();
  end.setHours(23, 59, 59, 0);
  end.setTime(end.getTime() - 3600 * 1000 * 24 * 1);
  const start = new Date();
  start.setHours(0, 0, 0, 0);
  start.setTime(start.getTime() - 3600 * 1000 * 24 * 101);
  dateRangeMonth.value = [formatDate(start, "month", "Start"), formatDate(end, "month", "End")];
  console.log(dateRangeMonth.value, "---dateRangeMonth.value");
}

//初始化天时间
function initDateOfDay() {
  const start = dayjs().subtract(1, "month").format("YYYY-MM-DD") + " 00:00:00";
  const end = dayjs().format("YYYY-MM-DD") + " 23:59:59";
  dateRangeDay.value = [start, end];
  console.log(dateRangeDay.value, "---dateRangeDay 天");
}
const dateRangeMin = ref([]);
// 设置默认时间为当前时间往前1小时到现在
const setDefaultTime = () => {
  const now = dayjs();
  const oneHourAgo = now.subtract(1, "hour");
  dateRangeMin.value = [oneHourAgo.format("YYYY-MM-DD HH:mm"), now.format("YYYY-MM-DD HH:mm")];
};

const timechange = val => {
  if (val == TimePeriodEnum.MONTHS) {
    initDateOfMonth();
    queryParams.value.startTime = `${dateRangeMonth.value[0].split(" ")[0]} 00:00:00`;
    queryParams.value.endTime = `${dateRangeMonth.value[1].split(" ")[0]} 23:59:59`;
  }
  if (val == TimePeriodEnum.YEAR) {
    queryParams.value.startTime = `${dateValue.value.startYear}-01-01 00:00:00`;
    queryParams.value.endTime = `${dateValue.value.endYear}-12-31 23:59:59`;
  }
  if (val == TimePeriodEnum.DAY) {
    initDateOfDay();
    queryParams.value.startTime = `${dateRangeDay.value[0].split(" ")[0]} 00:00:00`;
    queryParams.value.endTime = `${dateRangeDay.value[1].split(" ")[0]} 23:59:59`;
  }
  if (val == TimePeriodEnum.MINUTES) {
    setDefaultTime();
    queryParams.value.startTime = dateRangeMin.value[0];
    queryParams.value.endTime = dateRangeMin.value[1];
  }
};

const updateStatisticYear: any = (startYear: number, endYear: number) => {
  console.log("选中年份", startYear, endYear);
  queryParams.value.startTime = `${startYear}-01-01 00:00:00`;
  queryParams.value.endTime = `${endYear}-12-31 23:59:59`;
};

const changeTimeMonth = val => {
  console.log(val, "changeTimeMonth");
  if (val !== null) {
    queryParams.value.startTime = `${val[0]}-01 00:00:00`;
    queryParams.value.endTime = `${val[1]}-31 23:59:59`;
  } else {
    queryParams.value.startTime = null;
    queryParams.value.endTime = null;
  }
};

const changeTimeDay = val => {
  queryParams.value.startTime = `${val?.[0]} 00:00:00`;
  queryParams.value.endTime = `${val?.[1]} 23:59:59`;
};
const changeTimeMinutes = val => {
  queryParams.value.startTime = `${val?.[0]}`;
  queryParams.value.endTime = `${val?.[1]}`;
};

const formRef = ref(); // 筛选条件表单

// 重置表单
const resetTable = () => {
  formRef.value?.resetFields();
  initDate();
  queryData();
};
// 数据取字典值 映射
const points = reactive({
  pointPosition: "",
  AIPoint: ""
});

// 查图数据
const queryData = async () => {
  points.pointPosition = "";
  points.AIPoint = "";
  const area = `${queryParams.value.machineTask}_AI_COMMON`;
  // 数据字典
  const res: any = await queryChildByTypeCodeAndItemValue({
    value: `CALC_TASK_TYPE_COMMON`,
    typeCode: "ALGORITHM"
  });
  if (!res || !Array.isArray(res)) {
    return;
  }
  // 判断时间维度选择指标字典

  for (let i = 0; i < res.length; i++) {
    const el = res[i];
    if (area === el.itemValue) {
      const desc = JSON.parse(el.itemDesc);
      if (queryParams.value.timePeriod === TimePeriodEnum.MINUTES) {
        points.pointPosition = desc.point.paramName;
        points.AIPoint = desc.aiPoint.paramName;
      } else {
        points.pointPosition = desc.pointSpecial.paramName;
        points.AIPoint = desc.aiPoint.paramName;
      }
      break;
    }
  }
  if (!points.pointPosition || !points.AIPoint) {
    if (chartInstance) chartInstance?.dispose();
    PxMessage.info("区域暂无数据");
    return;
  } // 没查到字典映射值 无法调后续接口
  nextTick(() => {
    initChart();
  });
};
// 初始化时间筛选条件
const initDate = () => {
  queryParams.value.timePeriod = TimePeriodEnum.MINUTES;
  timechange(queryParams.value.timePeriod);
  queryParams.value.machineTask = areas.value[0].value;
  points.pointPosition = "";
  points.AIPoint = "";
};

// 初始化chart
const initChart = async () => {
  try {
    let params = {
      startTime: queryParams.value.startTime,
      endTime: queryParams.value.endTime,
      timePeriod: queryParams.value.timePeriod,
      paramList: [`${queryParams.value.machineTask}_AI_COMMON`]
    };
    const res = await queryDCCFutureAPI(params);
    renderChart(res);
  } catch (error) {
    console.log(error);
  }
};
const chartContainer = ref<DomType>(null);
let chartInstance = null;
const renderChart = result => {
  const TooltipNameMap = {
    [points.AIPoint]: "预测值",
    [points.pointPosition]: "实际值"
  };
  // X轴数据
  const resFirstItemAry = result.xaxis;
  let xAxisData = [];
  switch (queryParams.value.timePeriod) {
    case TimePeriodEnum.MINUTES:
      xAxisData = resFirstItemAry.map(item => item?.split(" ")[1]) || []; // minutes
      break;
    case TimePeriodEnum.DAY:
      xAxisData = resFirstItemAry.map(item => item?.split(" ")[0]) || []; // day
      break;
    case TimePeriodEnum.MONTHS:
      xAxisData = resFirstItemAry.map(item => item?.split(" ")[0].slice(0, 7)) || []; // month
      break;
    case TimePeriodEnum.YEAR:
      xAxisData = resFirstItemAry.map(item => item?.split(" ")[0].slice(0, 4)) || []; // year
      break;
    default:
      break;
  }
  // legend数据
  let legendData = [];
  Object.keys(TooltipNameMap).forEach(key => {
    legendData.push(key);
  });

  const seriesData = [];
  legendData.forEach(i => {
    const data = result.yaxis.find(item => item.name === i)?.value || [];
    let obj = {
      name: TooltipNameMap[i],
      type: "line",
      smooth: true,
      lineStyle: {
        type: "dashed",
        width: 1
      },
      tooltip: {
        valueFormatter: function (value) {
          console.log(`output->value`, value);
          return value != undefined ? `${value}kW` : "";
        }
      },
      data
    };
    seriesData.push(obj);
  });
  const option = {
    tooltip: {
      trigger: "axis",
      confine: true // 确保 tooltip 显示在容器内
    },
    title: {
      text: "WET Area DCC Load Analysis",
      left: "center"
    },
    legend: {
      left: "12%",
      top: 1,
      type: "scroll",
      data: legendData.map(item => TooltipNameMap[item])
    },
    grid: {
      left: "8%",
      right: "8%",
      top: "10%",
      bottom: "28%"
    },
    xAxis: [
      {
        type: "category",
        nameLocation: "center",
        nameGap: 25,
        data: xAxisData,
        axisPointer: {
          type: "shadow"
        },
        axisLabel: {
          rotate: 60 // 文字倾斜角度
        }
      }
    ],
    dataZoom: [
      {
        type: "slider",
        xAxisIndex: 0,
        start: 0,
        end: 100
      },
      {
        type: "inside",
        xAxisIndex: 0,
        zoomOnMouseWheel: true
      }
    ],
    yAxis: [
      {
        type: "value",
        name: "DCC Load(kW)",
        axisLine: { show: true },
        axisLabel: {
          formatter: "{value}"
        },
        min: function (value) {
          return Math.floor(value.min / 100) * 100 - 200;
        },
        max: function (value) {
          return Math.ceil(value.max / 100) * 100 + 200;
        }
      }
      // {
      //   type: "value",
      //   name: "External Temperature(°C)",
      //   nameTextStyle: {
      //     padding: [0, 20, 0, 0]
      //   },
      //   axisLine: { show: true },
      //   axisLabel: {
      //     formatter: "{value} °C"
      //   }
      // }
    ],
    series: seriesData
  };
  if (chartInstance) chartInstance?.dispose();
  chartInstance = echarts.init(chartContainer.value);
  chartInstance.clear();
  chartInstance.setOption(option);
};
// 初始化页面数据
const initPageData = async () => {
  initDate();
  await queryData();
};

onMounted(async () => {
  await getArea();
  initPageData();
});
onBeforeUnmount(() => {
  if (chartInstance) chartInstance?.dispose();
});

const radioChange = () => {
  queryData();
};
</script>
